#include <jni.h>

extern "C" {

int total = 0;

int clamp(int x, int a, int b) {
	return (x < a) ? a : (x > b) ? b : x;
}

JNIEXPORT void Java_hd_util_blur_Blur_blur(JNIEnv* env, jobject thiz, jintArray ja,
		jint jwidth, jint jheight, jint jradiu) {
	jsize jaLength = env->GetArrayLength(ja);
	int height = jheight;
	int width = jwidth;
	int *in = env->GetIntArrayElements(ja, 0);
	int *out = new int[height * width];
	int r = jradiu;
	int widthMinus1 = width - 1;

	int tableSize = 2 * r + 1;
	int *divide = new int[256 * tableSize];

	for (int i = 0; i < 256 * tableSize; i++)
		divide[i] = i / tableSize;
	int inIndex = 0;
	for (int y = 0; y < height; y++) {
		int outIndex = y;
		int ta = 0, tr = 0, tg = 0, tb = 0;
		for (int i = -r; i <= r; i++) {
			int rgb = in[inIndex + clamp(i, 0, width - 1)];
			ta += (rgb >> 24) & 0xff;
			tr += (rgb >> 16) & 0xff;
			tg += (rgb >> 8) & 0xff;
			tb += rgb & 0xff;
		}

		for (int x = 0; x < width; x++) {
			out[outIndex] = (divide[ta] << 24) | (divide[tr] << 16)
					| (divide[tg] << 8) | divide[tb];

			int i1 = x + r + 1;
			if (i1 > widthMinus1)
				i1 = widthMinus1;
			int i2 = x - r;
			if (i2 < 0)
				i2 = 0;
			int rgb1 = in[inIndex + i1];
			int rgb2 = in[inIndex + i2];

			ta += ((rgb1 >> 24) & 0xff) - ((rgb2 >> 24) & 0xff);
			tr += ((rgb1 & 0xff0000) - (rgb2 & 0xff0000)) >> 16;
			tg += ((rgb1 & 0xff00) - (rgb2 & 0xff00)) >> 8;
			tb += (rgb1 & 0xff) - (rgb2 & 0xff);
			outIndex += height;
		}
		inIndex += width;
	}

	env->SetIntArrayRegion(ja, 0, jaLength, out);
//	delete[] in;
//	delete[] out;
//	delete[] divide;
}

}
